<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Content;
use Illuminate\Support\Facades\View;
use TemplateService;

class HomeController extends Controller
{
    /**网站首页
     * @return mixed
     */
    public function home()
    {
        //为模板添加命名空间
        View::addNamespace('templates', public_path('templates'));
        $this->defineTemplate();
        return view('home');
    }


    /**
     * 栏目页
     *
     * @param Category $category
     * @return void
     */
    public function category(Category $category)
    {
        $this->defineTemplate();
        switch ($category->type) {
            case 1:
                //单个栏目标题+内容标题(从more到达这里)
                return view('list', compact('category'));
            case 2:
                //所有栏目+子栏目+内容标题(从导航链接到达这里)
                return view('index', compact('category'));
            case 3:
                //单文章栏目，读取栏目content内容
                return view($category->category_template, compact('category'));
            case 4:
                //外部链接，直接返回其url数据
                return $category;
        }
    }

    /**
     * 内容页
     *
     * @param Content $content
     * @return void
     */
    public function content(Content $content)
    {
        $this->defineTemplate();
        $content['click'] += 1;
        $content->save();
        return view('content', compact('content'));
    }

    /**
     *
     */
    protected function defineTemplate()
    {
        //获取已经安装的模板的name:default，默认为default类型
        $name = TemplateService::getActiveTemplate();
        try {
            //为模板添加指向的路径
            \View::addLocation(base_path("templates/{$name}"));
        } catch (Exception $e) {
            abort('404', '模板文件不存在');
        }
    }

    /**
     * 关于我们界面
     *
     */
    public function about()
    {
        View::addNamespace('templates', public_path('templates'));
        $this->defineTemplate();
        return view('about');
    }
}

